package model

import "time"

type User struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	BotanyList []*Botany `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type PlantingRecords struct {
	Id int64 `xorm:"pk autoincr"`
	UserId int64
	BotanyId int64
	BotanyName string
	CurrenWaterQuantity int
	CurrentStage int
	Mature bool
	FruitList []*Fruit `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Botany struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	StageList []*Stage `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Stage struct {
	Id int64 `xorm:"pk autoincr"`
	StageValue int
	BotanyId int64
	Name string
	WaterRequirement int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Fruit struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	PlantingRecordId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type WateringRecord struct {
	Id int64 `xorm:"pk autoincr"`
	UserId int64
	UserName string
	BotanyId int64
	BotanyName string
	BotanyStage int
	WaterQuantity int
	CreatedAt time.Time
	UpdatedAt time.Time
}

func MaxVaule(sList []*Stage)(int){

	maxVal := sList[0].StageValue

	for i := 0; i < len(sList); i++ {
		//从第二个元素开始循环比较，如果发现有更大的数，则交换
		if maxVal < sList[i].StageValue {
			maxVal = sList[i].StageValue
		}
	}

	return maxVal
}

func Watering(prId int64, wq int)(map[string]interface{}, error){

	var pr PlantingRecords
	x.Id(prId).Get(&pr)

	var s Stage
	x.Id(pr.CurrentStage).Get(&s)

	var sList []*Stage
	x.Where("botany_id = ?", pr.BotanyId).Find(&sList)

	if pr.CurrenWaterQuantity + wq >= s.WaterRequirement{
		if pr.CurrentStage < MaxVaule(sList){
			pr.CurrentStage += 1
			pr.CurrenWaterQuantity = wq - (s.WaterRequirement - pr.CurrenWaterQuantity)
		}else {
			pr.Mature = true

			for i:=1; i<=pr.CurrentStage; i++ {

				var f = Fruit{
					Name:             pr.BotanyName + "果实",
					PlantingRecordId: pr.Id,
					CreatedAt:        time.Now(),
					UpdatedAt:        time.Now(),
				}
				x.Insert(&f)
			}
		}
		x.Id(pr.Id).Update(&pr)
	}

	return map[string]interface{}{"message": "成功","code":200}, nil
}













































